const express = require('express');
const db = require('../mongodb/db');
const adminModel = require('../mongodb/models/adminModel');
const md5 = require('md5')
const multer = require('multer');
var router = express.Router();
const config = require('../mongodb/config')

const storage = multer.memoryStorage();
const upload = multer({ storage: storage });

db(() => {

})
/* GET users listing. */

// router.get('/test',(req,res,next)=>{
//     res.json({
//         msg:'hello!!',
//     })
// })
router.post('/reg', function (req, res, next) {
    adminModel.create({ account: req.body.account, password: md5(req.body.password) })
        .then(data => {
            res.json({
                code: '000',
                msg: '注册成功',
                data: data
            });
        })
        .catch(err => {
            return res.status(500).send('注册失败');
        });
       
   

});

router.post('/login', function (req, res, next) {
    let { account, password } = req.body
    adminModel.findOne({ account:account, password: md5(password) })
    .then(data=>{
        if (!data) {
            res.json({
                code:'001',
                msg:'账号或密码错误',
                data:data,
            })
            return
        }
        res.json({
            code:'000',
            msg:'登录成功',
            account:data.account,
            _id:data._id,
            admin:data.admin,
    })
    })
    .catch(err=>{
        if (err) {
            return res.status(500).send('登录失败')
        }
    })
   

})

router.post('/profile',upload.none(),async (req,res,next)=>{
    // console.log(req.file)
    try{
        const dataList={
            // avatar: req.file.buffer,
            avatar:req.body.avatar,
            userName:req.body.userName
        }
        const data=await adminModel.updateOne({ _id: req.body.uid },dataList)

        res.json({
            code: '000',
            msg: '修改个人资料成功',
           data:data
        })
    }catch(err){
        return res.status(500).send('修改个人资料失败')
    }

})


router.get('/profile', async (req, res, next) => {
    try {
       
        const data = await adminModel.findOne({ _id: req.query.uid })
      
        res.json({
            code: '000',
            msg: '获取个人资料成功',
            avatar: data.avatar || `http://${config.IP}:${config.hPort}/public/images/profile.jpg`,
            userName:data.userName||'未命名用户'
        })
    } catch (err) {
        return res.status(500).send('修改个人资料失败')
    }

})
module.exports = router;
